<?php

/**
 * @author lovebing <lovebing365@126.com> Created on 2015-5-10
 */
class AliPaymentCenter {

    const BASE_URL_PAY = 'http://pay.xiaowangtong.com.cn/alipay/start/';

    private $partner = '';
    private $key = '';
    private $sellerAccount = '';
    private $lastPaymentId = 0;
    private $orderNoPrefix = '';

    /**
     * 
     * @param type $partner
     * @param type $key
     * @param type $sellerAccount
     */
    public function __construct($partner, $key, $sellerAccount) {
        $this->partner = $partner;
        $this->key = $key;
        $this->sellerAccount = $sellerAccount;
    }

    /**
     * 
     * @param type $prefix
     */
    public function setOrderNoPrefix($prefix) {
        $this->orderNoPrefix = $prefix;
    }

    /**
     * 
     * @param type $orderNo
     * @param type $totalfee
     * @param type $paymentDesc
     * @param type $returnUrl
     * @param type $notifyUrl
     */
    public function createPayment($orderNo, $totalfee, $paymentDesc, $returnUrl, $notifyUrl) {
        $model = new PaymentAliModel();
        $model->seller_account_name = $this->sellerAccount;
        $model->partner = $this->partner;
        $model->md5_key = $this->key;
        $model->order_number = $this->orderNoPrefix . $orderNo;
        $model->totalfee = $totalfee;
        $model->payment_desc = $paymentDesc;
        $model->return_url = $returnUrl;
        $model->notify_url = $notifyUrl;
        $model->create_time = date('Y-m-d H:i:s');
        
        if(!$model->save()) {
            throw new RuntimeException(print_r($model->getErrors()));
        }
        
        $this->lastPaymentId = $model->id;
        return $model->id;
    }

    /**
     * 
     * @return type
     */
    public function getLastPaymentId() {
        return $this->lastPaymentId;
    }

    /**
     * 
     * @param type $id
     * @return type
     */
    public function getPayUrl($id = null) {
        if (is_null($id)) {
            $id = $this->lastPaymentId;
        }
        return self::BASE_URL_PAY . $id;
    }

}
